package com.xiaoquan.gulimall.product.service.impl;

import com.xiaoquan.gulimall.product.entity.SkuImagesEntity;
import com.xiaoquan.gulimall.product.entity.SpuInfoDescEntity;
import com.xiaoquan.gulimall.product.service.*;
import com.xiaoquan.gulimall.product.vo.SkuItemSaleAttrVo;
import com.xiaoquan.gulimall.product.vo.SkuItemVo;
import com.xiaoquan.gulimall.product.vo.SpuItemAttrGroupVo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoquan.common.utils.PageUtils;
import com.xiaoquan.common.utils.Query;

import com.xiaoquan.gulimall.product.dao.SkuInfoDao;
import com.xiaoquan.gulimall.product.entity.SkuInfoEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    ThreadPoolExecutor executor; // 这里注入的是自己在配置类中 配置的组件

    @Override
    @Transactional
    public Boolean changePrice(Long changeAmount) {
        SkuInfoEntity sku = getById(1l);
        sku.setPrice(new BigDecimal(sku.getPrice().longValue()+changeAmount));
        boolean b = updateById(sku);
        return b;
    }

    /**
     * 查询详情 查询sku的全部信息
     *  TODO 异步编程
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> { // supplyAsync 同步 有返回值的
            // 1、sku进本信息获取 标题、副标题、默认图片、价格 pms_sku_info
            SkuInfoEntity info = this.getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        },executor);
//        Long catalogId = info.getCatalogId(); // 获取sku对应的分类Id
//        Long spuId = info.getSpuId();  // 获取sku所属的spuId

        CompletableFuture<Void> saleFuture = infoFuture.thenAcceptAsync((res) -> { // 接收上一步的返回结果  自己无返回值
            // 3、获取spu的销售属性  根据skuId 找到对应的spu 再查出spu的销售属性
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        }, executor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            // 4、获取spu的介绍
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);
        }, executor);

        CompletableFuture<Void> baseFuture = infoFuture.thenAcceptAsync((res) -> {
            // 5、获取spu的规格参数信息
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        },executor);


        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> { // 异步操作
            // 2、sku的图片集合信息pms_sku_images
            List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        }, executor);

        CompletableFuture.allOf(saleFuture,descFuture,baseFuture,imageFuture).get(); // 只有当所有线程都完成了操作 才会执行这个操作
        // get()是阻塞的 只有等所有线程完成了 才能获取值
        return skuItemVo;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
        // this.save(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("sku_id",key).or().like("sku_name",key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)){
            wrapper.ge("price",min);  // wrapper.ge  大于等于 最小值 min
        }

        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)){
            try {
                BigDecimal bigDecimal = new BigDecimal("max");
                if (bigDecimal.compareTo(new BigDecimal("0"))== 1){
                    wrapper.le("price",max); // wrapper.le 小于等于 最大值 max
                }
            }catch (Exception e){

            }

        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id",spuId);
        List<SkuInfoEntity> list = this.list(wrapper);
        return  list;

    }

}